<template>
  <el-select
    :title="multiple ? optionData.label : ''"
    ref="select"
    :value="value"
    placeholder="请选择"
    :size="size"
    :clearable="clearable"
    :disabled="disabled"
    :filterable="filterable"
    :filter-method="filterMethod"
    style="width: 100%;"
    @clear="clear"
    @visible-change="visibleChange"
  >
    <el-option
      ref="option"
      hidden
      class="tree-select__option"
      :value="optionData.id"
      :label="optionData.label"
    >
    </el-option>
    <el-tree
      ref="tree"
      class="tree-select__tree"
      :class="`tree-select__tree--${multiple ? 'checked' : 'radio'}`"
      :node-key="nodeKey"
      :data="data"
      :props="props"
      :check-on-click-node="true"
      :default-expanded-keys="[value]"
      :show-checkbox="multiple"
      :highlight-current="!multiple"
      :expand-on-click-node="multiple"
      :default-expand-all="expand"
      :check-strictly="true"
      :filter-node-method="filterNode"
      @node-click="handleNodeClick"
      @check-change="handleCheckChange"
    ></el-tree>
  </el-select>
</template>
 
<script>
export default {
  name: "TreeSelect",
  props: {
    size: {
      type: String,
      default: "small"
    },
    // v-model绑定
    value: {
      type: [String, Number],
      default: ""
    },
    multiple: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: false
    },
    // 树形的数据
    data: {
      type: Array,
      default: function() {
        return [];
      }
    },
    // 每个树节点用来作为唯一标识的属性
    nodeKey: {
      type: [String, Number],
      default: "fid"
    },
    filterable: {
      type: Boolean,
      default: false
    },
    expand: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    // tree的props配置
    props: {
      type: Object,
      default: function() {
        return {
            children: 'children',
            label: 'menuName',
            id: 'fid'
        };
      }
    },
    // 父节点是否可选
    parentSelectable: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      optionData: {
        id: "",
        label: ""
      },
      filterFlag: false
    };
  },
  watch: {
    value: {
      handler(val) {
        if (!this.isEmpty(this.data)) {
          this.init(val);
        }
      },
      immediate: true
    },
    data: function(val) {
      if (!this.isEmpty(val)) {
        this.init(this.value);
      }
    }
  },
  created() {},
  methods: {
    // 是否为空
    isEmpty(val) {
      for (let key in val) {
        return false;
      }
      return true;
    },
    handleNodeClick(data, node) {
      if (this.multiple) {
        // let pNode = this.$refs.tree.getNode(node).parent.data;
	      // console.log(pNode,99999)//获得点击节点父节点的**数据**
        // this.$emit('getparentId',pNode.fid)
        return;
      }
      if (!this.parentSelectable) {
        this.$refs.tree.setCurrentKey(data.id);
        if (data.children && data.children.length) {
          return;
        }
      }
      

      this.$emit("input", data[this.nodeKey]);
      this.$emit("select", data, node);
      this.$refs.select.visible = false;
    },
    handleCheckChange(node, bool, child) {
      console.log(node)
      const nodes = this.$refs.tree.getCheckedNodes();
      const value = nodes.map(item => item[this.nodeKey]).join(",");
      // console.log(nodes,111)
      // let temp = value.split(',')
      // temp.push(node.parentId)
      // let temp1 = temp.join(",")
      // // temp1.join(",")
      // console.log(temp1)
      this.$emit("input", value);
      // this.$emit('handleValue',temp1)
    },
    init(val) {
      // 多选
      if (this.multiple) {
        const arr = val.toString().split(",");
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys(arr);
          const nodes = this.$refs.tree.getCheckedNodes();
          this.optionData.id = val;
          this.optionData.label = nodes
            .map(item => item[this.props.label])
            .join(",");
            console.log(this.optionData)
        });
      }
      // 单选
      else {
        val = val === "" ? null : val;
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(val);
          if (val === null) {
            return;
          }
          const label = this.props.label || "label";
          const node = this.$refs.tree.getNode(val);
          this.optionData.id = val;
          this.optionData[label] = node.label;
        });
      }
    },
    visibleChange(e) {
      if (e) {
        const tree = this.$refs.tree;
        this.filterFlag && tree.filter("");
        this.filterFlag = false;
        let selectDom = null;
        if (this.multiple) {
          selectDom = tree.$el.querySelector(".el-tree-node.is-checked");
        } else {
          selectDom = tree.$el.querySelector(".is-current");
        }
        setTimeout(() => {
          this.$refs.select.scrollToOption({ $el: selectDom });
        }, 0);
      }
    },
    clear() {
      this.$emit("input", "");
    },
    filterMethod(val) {
      this.filterFlag = true;
      this.$refs.tree.filter(val);
    },
    filterNode(value, data) {
      if (!value) return true;
      const label = this.props.label || "name";
      return data[label].indexOf(value) !== -1;
    }
  }
};
</script>
 
<style>
.tree-select__option.el-select-dropdown__item {
  height: auto;
  line-height: 1;
  padding: 0;
}
.tree-select__tree {
  font-weight: 400;
}
.tree-select__tree.tree-select__tree--radio .el-tree-node.is-current > .el-tree-node__content {
  background-color: #1263dd !important;
  color: #fff !important;
  font-weight: bold;
}
.tree-select__tree.tree-select__tree--radio .el-tree-node__content:hover {
  background-color: #0f428f;
  color: #fff;
}

</style>